//
//  FourthViewController.m
//  MvcTest
//
//  Created by SDMac on 15/5/11.
//  Copyright (c) 2015年 SDMac. All rights reserved.
//

#import "FourthViewController.h"

#define MYBUNDLE_NAME @ "mapapi.bundle"
#define MYBUNDLE_PATH [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent: MYBUNDLE_NAME]
#define MYBUNDLE [NSBundle bundleWithPath: MYBUNDLE_PATH]

@interface RouteAnnotation : BMKPointAnnotation
{
    int _type; ///<0:起点 1：终点 2：公交 3：地铁 4:驾乘 5:途经点
    int _degree;
}

@property (nonatomic) int type;
@property (nonatomic) int degree;
@end

@implementation RouteAnnotation

@synthesize type = _type;
@synthesize degree = _degree;
@end

@interface FourthViewController ()

@end

@implementation FourthViewController

#pragma mark ---- life cycle

- (void)loadView
{
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenBunds.size.width, ScreenBunds.size.height)];
    
    self.view = view;
    
    self.view.backgroundColor = [UIColor grayColor];
    
    self.routeSearch = [[BMKRouteSearch alloc]init];
    
    self.searcher =[[BMKPoiSearch alloc]init];
    
    self.mapView = [[BMKMapView alloc]initWithFrame:CGRectMake(0, 64, ScreenBunds.size.width, ScreenBunds.size.height - 157)];
    self.mapView.zoomLevel = 17.0;
    [self.view addSubview:self.mapView];
    
    UIButton *btnA = [self getButtonWithTitle:@"中心" tag:1];
    [self.view addSubview:btnA];
    
    UIButton *btnB = [self getButtonWithTitle:@"标注" tag:2];
    [self.view addSubview:btnB];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
    self.title = @"第四";
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    RootViewController *root=(RootViewController *)self.tabBarController;
    [root setTabarHiend:NO];
    self.navigationController.navigationBarHidden=NO;
    
    [self.mapView viewWillAppear];
    self.mapView.delegate = self;
    self.searcher.delegate = self;
    self.routeSearch.delegate = self;
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    
    [self.mapView viewWillDisappear];
    self.mapView.delegate = nil;
    self.searcher.delegate = nil;
    self.routeSearch.delegate = self;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark ---- BMKMapViewDelegate

- (BMKAnnotationView *)mapView:(BMKMapView *)mapView viewForAnnotation:(id <BMKAnnotation>)annotation
{
    static NSString *poiName = @"myAnnotation";
    
    if ([annotation isKindOfClass:[BMKPointAnnotation class]])
    {
        BMKPinAnnotationView *newAnnotationView = (BMKPinAnnotationView*)[_mapView dequeueReusableAnnotationViewWithIdentifier:poiName];
        
        if (!newAnnotationView)
        {
            newAnnotationView = [[BMKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:poiName];
        }
        
        newAnnotationView.pinColor = BMKPinAnnotationColorPurple;
        newAnnotationView.animatesDrop = YES;// 设置该标注点动画显示
        
        NSLog(@"name:%@",annotation.title);
        
        return newAnnotationView;
    }
    
    return nil;
}

#pragma mark ---- BMKRouteSearchDelegate

- (void)onGetDrivingRouteResult:(BMKRouteSearch*)searcher result:(BMKDrivingRouteResult*)result errorCode:(BMKSearchErrorCode)error
{
    NSArray* array = [NSArray arrayWithArray:_mapView.annotations];
    [_mapView removeAnnotations:array];
    array = [NSArray arrayWithArray:_mapView.overlays];
    [_mapView removeOverlays:array];
    if (error == BMK_SEARCH_NO_ERROR) {
        BMKDrivingRouteLine* plan = (BMKDrivingRouteLine*)[result.routes objectAtIndex:0];
        // 计算路线方案中的路段数目
        int size = [plan.steps count];
        int planPointCounts = 0;
        for (int i = 0; i < size; i++) {
            BMKDrivingStep* transitStep = [plan.steps objectAtIndex:i];
            if(i==0){
                RouteAnnotation* item = [[RouteAnnotation alloc]init];
                item.coordinate = plan.starting.location;
                item.title = @"起点";
                item.type = 0;
                [_mapView addAnnotation:item]; // 添加起点标注
                
            }else if(i==size-1){
                RouteAnnotation* item = [[RouteAnnotation alloc]init];
                item.coordinate = plan.terminal.location;
                item.title = @"终点";
                item.type = 1;
                [_mapView addAnnotation:item]; // 添加起点标注
            }
            //添加annotation节点
            RouteAnnotation* item = [[RouteAnnotation alloc]init];
            item.coordinate = transitStep.entrace.location;
            item.title = transitStep.entraceInstruction;
            item.degree = transitStep.direction * 30;
            item.type = 4;
            [_mapView addAnnotation:item];
            
            //轨迹点总数累计
            planPointCounts += transitStep.pointsCount;
        }
        // 添加途经点
        if (plan.wayPoints) {
            for (BMKPlanNode* tempNode in plan.wayPoints) {
                RouteAnnotation* item = [[RouteAnnotation alloc]init];
                item = [[RouteAnnotation alloc]init];
                item.coordinate = tempNode.pt;
                item.type = 5;
                item.title = tempNode.name;
                [_mapView addAnnotation:item];
            }
        }
        //轨迹点
        BMKMapPoint * temppoints = new BMKMapPoint[planPointCounts];
        
        int i = 0;
        for (int j = 0; j < size; j++) {
            BMKDrivingStep* transitStep = [plan.steps objectAtIndex:j];
            int k=0;
            for(k=0;k<transitStep.pointsCount;k++) {
                temppoints[i].x = transitStep.points[k].x;
                temppoints[i].y = transitStep.points[k].y;
                i++;
            }
            
        }
        // 通过points构建BMKPolyline
        BMKPolyline* polyLine = [BMKPolyline polylineWithPoints:temppoints count:planPointCounts];
        [_mapView addOverlay:polyLine]; // 添加路线overlay
        
        delete []temppoints;
        
        
    }
}

#pragma mark ---- PoiSearchDeleage

- (void)onGetPoiResult:(BMKPoiSearch*)searcher result:(BMKPoiResult*)poiResultList errorCode:(BMKSearchErrorCode)error
{
    if (error == BMK_SEARCH_NO_ERROR)
    {
        //在此处理正常结果
        NSMutableArray *poiAry = [NSMutableArray arrayWithCapacity:poiResultList.poiInfoList.count];
        
        for (BMKPoiInfo *poiInfo in poiResultList.poiInfoList)
        {
            BMKPointAnnotation* annotation = [[BMKPointAnnotation alloc]init];
            annotation.coordinate = poiInfo.pt;
            annotation.title = poiInfo.name;
            annotation.subtitle = poiInfo.address;
            [poiAry addObject:annotation];
        }
        [self.mapView addAnnotations:poiAry];
    }
    
    else if (error == BMK_SEARCH_AMBIGUOUS_KEYWORD)
    {
        //当在设置城市未找到结果，但在其他城市找到结果时，回调建议检索城市列表
        // result.cityList;
        NSLog(@"起始点有歧义");
    }
    else
    {
        NSLog(@"抱歉，未找到结果");
    }
}

#pragma mark ---- CustomDelegate

#pragma mark ---- event response

-(void)getAction:(UIButton*)sender
{
    if ([sender.titleLabel.text isEqualToString:@"路径"])
    {
        BMKPlanNode* start = [[BMKPlanNode alloc]init];
        start.pt = CLLocationCoordinate2DMake(31.289292,121.453384);
        
        BMKPlanNode* end = [[BMKPlanNode alloc]init];
        
        end.pt = CLLocationCoordinate2DMake(31.395625,121.448237);;
        
        BMKDrivingRoutePlanOption *transitRoute = [[BMKDrivingRoutePlanOption alloc]init];
        transitRoute.from = start;
        transitRoute.to = end;
        BOOL flag = [self.routeSearch drivingSearch:transitRoute];
        
        if(flag)
        {
            NSLog(@"路径检索发送成功");
        }
        else
        {
            NSLog(@"路径检索发送失败");
        }
    }
    else if ([sender.titleLabel.text isEqualToString:@"中心"])
    {
        BMKNearbySearchOption *option = [[BMKNearbySearchOption alloc]init];
        option.pageIndex = 1;
        option.pageCapacity = 10;
        option.location = CLLocationCoordinate2DMake(31.289292,121.453384);
        option.keyword = @"小吃";
        
        BOOL flag = [self.searcher poiSearchNearBy:option];
        if(flag)
        {
            NSLog(@"周边检索发送成功");
        }
        else
        {
            NSLog(@"周边检索发送失败");  
        }
        
        self.mapView.centerCoordinate = CLLocationCoordinate2DMake(31.289292,121.453384);
    }
    else
    {
        NSMutableArray *detailsAry=[NSMutableArray arrayWithCapacity:4];
        
        BMKPointAnnotation *poiA = [[BMKPointAnnotation alloc] init];
        poiA.coordinate = CLLocationCoordinate2DMake(31.289292,121.453384);
        poiA.title = @"昆仑";
        poiA.subtitle = @"灵石路656号";
        [detailsAry addObject:poiA];
        
        BMKPointAnnotation *poiB = [[BMKPointAnnotation alloc] init];
        poiB.coordinate = CLLocationCoordinate2DMake(31.289438,121.454086);
        poiB.title = @"峨眉";
        poiB.subtitle = @"大宁路656号";
        [detailsAry addObject:poiB];
        
        BMKPointAnnotation *poiC = [[BMKPointAnnotation alloc] init];
        poiC.coordinate = CLLocationCoordinate2DMake(31.289253,121.452993);
        poiC.title = @"青城";
        poiC.subtitle = @"广中路656号";
        [detailsAry addObject:poiC];
        
        self.mapView.centerCoordinate = CLLocationCoordinate2DMake(31.289292,121.453384);
        
        [self.mapView addAnnotations:detailsAry];
    }
}

#pragma mark ---- private methods

#pragma mark ---- getters and setters

-(UIButton*)getButtonWithTitle:(NSString*)title tag:(NSInteger)tag
{
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.tag = tag;
    btn.titleLabel.font = [UIFont systemFontOfSize:17];
    btn.frame = CGRectMake((tag - 1) * (ScreenBunds.size.width / 2.0),ScreenBunds.size.height - 93, ScreenBunds.size.width / 2.0, 44);
    [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [btn setTitle:title forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(getAction:) forControlEvents:UIControlEventTouchUpInside];
    
    return btn;
    
}


@end
